package org.bookie.init.components;

import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;

import org.apache.hivemind.ApplicationRuntimeException;
import org.apache.hivemind.Registry;
import org.apache.tapestry.BaseComponent;
import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.annotations.ComponentClass;
import org.apache.tapestry.annotations.InjectObject;
import org.apache.tapestry.annotations.Parameter;
import org.apache.tapestry.services.ApplicationGlobals;
import org.bookie.init.InitTask;

@ComponentClass
public abstract class Tasks extends BaseComponent {

	private static final String REGISTRY_KEY_PREFIX = "org.apache.tapestry.Registry:";
	
	@Parameter(required = true)
	public abstract Collection<InitTask> getTasks();
	
	@InjectObject("service:tapestry.globals.ApplicationGlobals")
	public abstract ApplicationGlobals getGlobals();
	
	@Override
	protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle) {
		super.renderComponent(writer, cycle);
		Registry registry = findRegistry();
		for (InitTask task : getTasks()) {
			writer.begin("h2");
			writer.printRaw(task.getTitle());
			writer.end();
			writer.begin("h3");
			writer.printRaw("Checking phase");
			writer.end();
			Properties check = check(task, registry);
			if (check != null) {
				writeTable(writer, check);
			}
			writer.begin("h3");
			writer.printRaw("Executing phase");
			writer.end();
			Properties execute = execute(task, registry);
			if (execute != null) {
				writeTable(writer, execute);
			}
		}
	}

	
	private Registry findRegistry() {
		return (Registry) getGlobals().getServletContext().getAttribute(REGISTRY_KEY_PREFIX + "app");
	}

	private Properties check(InitTask task, Registry registry) {
		try {
			return task.check(registry);
		} catch (Exception e) {
			throw new ApplicationRuntimeException(e);
		}
	}

	private Properties execute(InitTask task, Registry registry) {
		try {
			return task.execute(registry);
		} catch (Exception e) {
			throw new ApplicationRuntimeException(e);
		}
	}
	
	
	/**
	 * Writes table from properties
	 * @param writer
	 * @param properties
	 */
	private void writeTable(IMarkupWriter writer, Properties properties) {
		writer.begin("table");
		writer.appendAttribute("class", "props");
		for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) {
			String key= (String) iter.next();
			writer.begin("tr"); 
			{
				writer.begin("td");
				writer.appendAttribute("nowrap", "nowrap");
				writer.print(key + ":");
				writer.end();
				writer.begin("th");
				writer.print(properties.getProperty(key));
				writer.end();
			}
			writer.end();
		}
		writer.end();
	}
		
}
